package com.alex.springbootdemo.exception;

import cn.hutool.core.util.ObjectUtil;
import com.alex.springbootdemo.common.CommonResult;
import com.alex.springbootdemo.common.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice
@Slf4j
public class GlobalExceptionHandle {

    @ExceptionHandler(Exception.class)
    public @ResponseBody CommonResult handlerAllException(Exception e) {
        e.printStackTrace();
        log.error("global catch exception,detail:{}", e.getMessage());
        if (e instanceof AssertException) {
            AssertException assertException = (AssertException) e;
            ResultCode resultCode = assertException.getResultCode();
            String errMsg = assertException.getErrMsg();
            return CommonResult.failed(resultCode == null ? ResultCode.ASSERT_ERROR : resultCode,
                    ObjectUtil.isNotNull(errMsg) ? errMsg : null);
        }
        if (e instanceof MethodArgumentNotValidException) {
            MethodArgumentNotValidException methodArgumentNotValidException = (MethodArgumentNotValidException) e;
            BindingResult bindingResult = methodArgumentNotValidException.getBindingResult();
            String defaultMessage = bindingResult.getFieldErrors().get(0).getDefaultMessage();
            return CommonResult.validateFailed(defaultMessage);
        }
        return CommonResult.failed(e.getMessage());
    }
}
